package com.zhibang.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhibang.dto.AccountxtzhDTO;
import com.zhibang.entity.Account;
import com.zhibang.service.AccountRoleService;
import com.zhibang.service.AccountService;
import com.zhibang.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AccountController{
    @Resource
    private AccountService accountService;
    @Resource
    private AccountRoleService ar;

    @RequestMapping("login")
    public Result login(@RequestBody Account u){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(u.getAccount(),u.getPassword());
        try {
            subject.login(token);
            // 取出当前用户信息
            Account account = (Account) subject.getPrincipal();
            // 以当前会话的id作为token(令牌)响应到浏览器
            String sessionID = subject.getSession().getId().toString();
            Map<String, Object> map = new HashMap<>();
            map.put("token",sessionID);
            map.put("username",account.getName());

            return Result.data(map);
        } catch (UnknownAccountException e) {
            return Result.fail("用户名不存在");
        } catch (LockedAccountException e) {
            return Result.fail("您的账户已被锁定,请联系管理员");
        } catch (IncorrectCredentialsException e) {
            return Result.fail("密码输入错误");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("认证失败");
        }
    }

    @RequestMapping("logout")
    public Result logout(){
        Subject subject = SecurityUtils.getSubject();
        // 注销
        subject.logout();
        return Result.ok("注销成功");
    }

    @RequestMapping("findAccountById")
    public Result findAccountById(@RequestBody Account account) {
        // 取出当前用户信息
        Subject subject = SecurityUtils.getSubject();
        // 将前用户信息返回给前台
        Account user = (Account) subject.getPrincipal();
        return Result.data(user);
    }
    //根据id修改
    @RequestMapping("updateAccount")
    public Result updateAccount(@RequestBody Account account) {
        // 获取当前用户
        Subject subject = SecurityUtils.getSubject();
        Account user = (Account) subject.getPrincipal();
        // 修改当前用户
        account.setId(user.getId());
        // 更新用户信息
        boolean b = accountService.updateById(account);
        return b ? Result.ok("修改成功") : Result.fail("修改失败");
        // 返回修改后的用户信息
    }

    @RequestMapping("list/{pageNum}/{pageSize}")
    public Result list(
            @PathVariable Integer pageNum,
            @PathVariable Integer pageSize,
            @RequestBody AccountxtzhDTO query){
        IPage<AccountxtzhDTO> pager = new Page<>(pageNum,pageSize);
        accountService.selectAccountInfo(query,pager);
        return Result.data(pager);
    }
    //重置密码数据库密码要加密Account
    @RequestMapping("resetPassword/{id}")
    public Result resetPassword(@PathVariable Integer id, @RequestBody Map<String, String> request) {
        String newPassword = request.get("newPassword");
        String encryptedPassword = new SimpleHash("MD5", newPassword, null, 2).toHex();
        boolean success = accountService.updatePasswordById(id, encryptedPassword);
        return success ? Result.ok("重置密码成功") : Result.fail("重置密码失败");
    }
    //修改用户状态
    @RequestMapping(value = "updateStateById/{id}", method = RequestMethod.POST)
    public Result updateStateById(@PathVariable Integer id, @RequestBody Map<String, Integer> request) {
        Integer state = request.get("state");
        boolean success = accountService.updateStateById(id, state);
        return success ? Result.ok("状态更新成功") : Result.fail("状态更新失败");
    }

}
